﻿using CommonDevelop;
using CommonDevelop.Scene;
using CommonEngine;
using CommonFP;
using ManageDto;
using ManageService;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebAdmin.Handler;

namespace WebAdmin.Areas.Org.Controllers
{
    /// <summary>
    /// 组织架构
    /// </summary>
    [Area("Org")]
    [Route("Org/[controller]/[action]")]
    public class OrgUserController : BaseController
    {
        private readonly IUserService _UserService;
        private readonly IDeptService _DeptService;
        private readonly IPositionService _PostService;
        /// <summary>
        /// 构造注入
        /// </summary>
        public OrgUserController(IUserService UserService, IDeptService DeptService, IPositionService PostService)
        {
            this._UserService = UserService;
            this._DeptService = DeptService;
            this._PostService = PostService;
        }

        /// <summary>
        /// 视图列表
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Title = "组织架构";
            return View();
        }

        /// <summary>
        /// 选择岗位配置
        /// </summary>
        [HttpGet]
        public ActionResult GetSelectLayer()
        {
            ViewBag.Title = "配置岗位";
            return View();
        }

        #region--Select--

        /// <summary>
        /// 组织树
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetOrgTree()
        {
            List<OrgDto> OrgLs = new List<OrgDto>();
            List<CompanyDto> comLs = this._DeptService.GetCompany().ToList();
            if (comLs == null)
                return this.Fail("没有企业数据");

            foreach (var com in comLs)
            {
                OrgDto OM = new OrgDto()
                {
                    NodeId = com.CompanyId,
                    ParentId = com.ParentId,
                    NodeName = com.FullName,
                    Icon = "glyphicon glyphicon-book",
                    IsCom = true
                };
                OrgLs.Add(OM);

                List<DeptDto> deptLs = this._DeptService.GetDeptByCompanyId(com.CompanyId).ToList();
                if (deptLs == null)
                    continue;

                foreach (var dept in deptLs)
                {
                    OrgDto OM2 = new OrgDto()
                    {
                        NodeId = dept.DeptId,
                        ParentId = dept.ParentId,
                        NodeName = dept.FullName,
                        Icon = "glyphicon glyphicon-bookmark",
                        IsCom = false
                    };

                    if (OM2.ParentId.IsEmpty())
                        OM2.ParentId = OM.NodeId;

                    OrgLs.Add(OM2);
                }
            }

            var Data = BizPage.GetOrgTree(OrgLs);
            return this.ToJsonContent(Data);
        }

        /// <summary>
        /// 取树节点信息
        /// </summary>
        [HttpPost]
        [AjaxOnly]
        public ActionResult GetDeptCom(string id)
        {
            ComDeptDto box = this._DeptService.GetDeptItem(id);
            if (box == null)
                return this.Fail("NULL");
            else
                return this.SuccessJson(box);
        }

        /// <summary>
        /// 视图列表查询（分页）
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string companyId, string deptId, string keyword)
        {
            Pagination pag = pagination.ToObject<Pagination>();
            List<UserDto> data = this._UserService.GetDtosSets(pag, companyId, deptId, keyword).ToList();
            var jsonData = new
            {
                rows = data,
                total = pag.total,
                page = pag.page,    //由前端配置
                records = pag.records
            };
            return this.SuccessJson(jsonData);
        }

        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPostCheck(string id)
        {
            List<PositionDto> data = this._PostService.GetList<PositionDto>().ToList();
            var Ls = this._PostService.GetUserPosition(id).Select(a => a.PositionId);
            if (Ls.IsNotNullOrEmpty())
                foreach (var v in data)
                    if (Ls.Contains(v.PositionId))
                        v.Sort = 1;

            return this.SuccessJson(data);
        }

        #endregion

        #region--增删改--

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeAdd(string companyId, string deptId)
        {
            UserDto en = new UserDto();
            en.JobNumber = this._UserService.BuildSeq();
            en.CompanyId = companyId;
            en.DepartmentId = deptId;
            en.ApplyKey = this.Current.ApplyKey;
            en.HeadIcon = "/Playground/Content/patterns/defU.jpg";
            return this.SuccessJson(en);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeDelete(string keyValue)
        {
            Validation<bool> vb = this._UserService.Delete(keyValue);
            var ValTuple = vb.Outcome(a => a);
            if (ValTuple.Errors.IsEmpty())
                return ValTuple.result ? this.Success("操作成功") : this.Fail("操作失败");
            else
                return this.Fail(ValTuple.Errors);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeEdit(string keyValue)
        {
            var outcome = this._UserService.Get<UserDto>(keyValue);
            return outcome.Match(() => this.Fail("Null Error"),
                en =>
                {
                    List<PositionDto> box = this._PostService.GetUserPosition(en.UserId).ToList();
                    if (box.IsNotNullOrEmpty())
                        box.Select(a => a.FullName)
                        .MergeDistinct()
                        .Match(() => en.PostTitle = "", a => en.PostTitle = a);
                    else
                        en.PostTitle = "";
                    return this.SuccessJson(en);
                });
        }

        [HttpPost]
        [AjaxOnly]
        [DisableRequestSizeLimit]
        public ActionResult NodeSave([FromForm]string DataText)
        {
            UserDto em = PageUtility.FormMap<UserDto>(DataText);
            if (em == null)
                return this.Fail("表单解读失败");
            if (em.FullName.IsEmpty())
                return this.Fail("用户名称不能为空");
            if (em.Account.IsEmpty())
                return this.Fail("用户账户不能为空");

            if (this._UserService.ExistAccount(em.Account, em.UserId))
                return this.Fail("账号已经被使用");

            if (!em.HeadIcon.IsEmpty())
                if (em.HeadIcon.Contains("Playground"))
                    em.HeadIcon = "/Playground/Content/patterns/defU.jpg";

            Validation<bool> vb = FP.Error("未执行");
            if (em.ModifyUserId.IsEmpty())
                vb = this._UserService.Add(em);
            else
                vb = this._UserService.Save(em);

            var ValTuple = vb.Outcome(a => a);
            if (ValTuple.Errors.IsEmpty())
                return ValTuple.result ? this.Success("操作成功") : this.Fail("操作失败");
            else
                return this.Fail(ValTuple.Errors);
        }

        #endregion

        #region--扩展保存岗位--

        [HttpPost]
        [AjaxOnly]
        public ActionResult SaveUserPost([FromForm] CollectDto Dto)
        {
            string UID = Dto.EnId;
            string PostIds = Dto.ContentTxt;
            string PostTitle = "";
            var Ls = CommonOP.SplitList(PostIds, ',');
            if (Ls.IsNotNullOrEmpty())
            {
                var ok = this._PostService.UserRelationPosition(UID, Ls.ToArray());
                if (ok)
                {
                    List<PositionDto> box = this._PostService.GetUserPosition(UID).ToList();
                    if (box.IsNotNullOrEmpty())
                        box.Select(a => a.FullName)
                        .MergeDistinct()
                        .Match(() => PostTitle = "", a => PostTitle = a);
                    else
                        PostTitle = "";
                }
            }
            return this.Success(PostTitle);
        }

        #endregion

    }
}